import torch
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from torch import nn

"""
逻辑分类问题测试
"""
data = pd.read_csv('dataset/credit-a.csv', header=None)

# 特征值，前15列
X = data.iloc[:, :-1]
# 取最后一列
Y = data.iloc[:, -1].replace(-1, 0)
X = torch.from_numpy(X.values).type(torch.float32)
# 把Y值转化为，集合，集合元素为一个元素的数组，方便计算
Y = torch.from_numpy(Y.values.reshape(-1, 1)).type(torch.float32)

# 创建模型
model = nn.Sequential(
    # 线性层
    nn.Linear(15, 1),
    # Sigmoid层
    nn.Sigmoid()
)

# 初始化损失函数，二元交叉熵损失函数，对应0和1的结果
loss_fn = nn.BCELoss()
# 前序梯度下降法
opt = torch.optim.Adam(model.parameters(), lr=0.0001)

# 小批次训练
# 每次训练多少个数据
batches = 16
# 需要多少个批次
no_of_batch = 653 // 16
for epoch in range(1000):
    for i in range(no_of_batch):
        start = i * batches
        end = start + batches
        x = X[start:end]
        y = Y[start: end]
        y_pred = model(x)
        loss = loss_fn(y_pred, y)
        # 清空梯度
        opt.zero_grad()
        loss.backward()
        opt.step()

# 查看权重
print(model.state_dict())
# 用均值测试计算正确率
a = ((model(X).data.numpy() > 0.5).astype('int') == Y.numpy()).mean()
print(a)
